<?php


namespace addons\facrm\library\notice\queue;

use app\admin\model\Admin;
use app\common\library\Email;
use think\Log;
use think\Queue;
use think\queue\job;
use think\Validate;

/**
 * 发票队列
 * Class InvoiceJob
 * @package addons\facrm\library\notice\queue
 */
class InvoiceJob
{
    public function fire(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
            $job->delete();
            return;
        }
        //获取对象内容
        $model_info = null;
        if (isset($data['model_id']) && $data['model_id']) {
            $model_info = model('\app\admin\model\facrm\Invoice')->find($data['model_id']);
        }
        if (!$model_info) {
            $job->delete();
            return;
        }
        $model_info = $model_info->toArray();
        $settingModel = new \app\admin\model\facrm\Setting();

        //邮件通知、邮件队列,通知客户
        if ($model_info && isset($model_info['email']) && $model_info['email']) {
            //获取邮件模板
            $setting = $settingModel->where('key', 'invoice_tpl')->value('values');
            $setting = json_decode($setting, true);
            $send_data = [
                'subject' => __("您的票据已经开具,序号{$model_info['id']}"),//发票QQ邮箱会触发广告，自定义先不做
                'to' => $model_info['email'],
                'message' => __($setting['emailtpl'], $model_info)
            ];

            //附件拆分
            $files = explode(",", $model_info['files']);
            $urlstr = '';
            foreach ($files as $k => $url) {
				$k++;
                $urlstr .= $url ? "<a href='" . cdnurl($url, true) . "' >附件{$k}</a><br/>" : '';
            }
            if ($urlstr)
                $send_data['message'] .= "<br/>票据附件：<br/>" . $urlstr;
			
            Queue::push("addons\\facrm\\library\\queue\\EmailJob", $send_data);
        }

        //通知申请开票人
        $key = "notice_invoice_opener";
        $data['admin_ids'] = $model_info['create_admin_id'];

        $notice_types = \addons\facrm\library\notice\Notice::getProviders();
        $keys = "";
        foreach ($notice_types as $v) {
            $keys .= $keys ? ',' . $key . $v : $key . $v;
        }


        $setinglist = $settingModel->where('key', 'in', $keys)->where('status', 1)->select();

        if (!$setinglist) {
            $job->delete();
            return false;
        }
        Log::write("__________InvoiceJob_______");
        foreach ($setinglist as $r) {
            if (!$r->values['engine']) continue;
            $notice_app = new \addons\facrm\library\notice\Notice(['key' => $r->values['engine']]);
            $notice_app->send($r, $data, $model_info);
        }
        $job->delete();
        return true;

    }

    public function failed($data)
    {
        Log::write("开票成功相关通知：" . print_r(['data' => $data,], true), 'error');
    }

}